import { mkApi } from "../utils/monkeyTool/monkeyApi";
export interface UrlInfo {
  path:string,
  name:string,
  fulUrl:string,
  pathName:string,
  select:boolean,
  port:string
}
interface Vue_HTMLDivElement extends HTMLDivElement {
  __vue__?:any,
  __vue_app__?:{
    config:{
      globalProperties:{
        $router:{
          options:{
            history:{
              base:string
            },
            routes:Array<{name:string,path:string,component:any}>
          }
        }
      }
    },
    version:string
  }
}
const pathNameApi = {
  // 获取路由参数,通过[serverName:"",searchValue:""]储存多个项目的信息
  getSearchValue(baseUrl:string) {
    if(!location.href.includes("localhost")) return ""
    let searchValue:string = location.search ? location.search.slice(1) : ""
    let searchValueList = mkApi.SEARCH_VALUE.get()
    let findItem = null
    if(searchValueList && searchValueList?.length > 0){
      findItem =  searchValueList?.find(res => baseUrl.includes(res.serverName))
    }
    // 当前页面有searchValue，储存；无searchValue，智能填充
    const valueApi = {
      saveValue(searchValue:string){
        if(!searchValue) return
        // 判断当前SEARCH_VALUE内是否储存过信息，有则替换，无则储存
        if(searchValueList.length === 0 || !findItem){
          searchValueList.push({serverName:baseUrl.replaceAll("/",""), searchValue})
        }else{
          findItem.searchValue = searchValue
        }
        mkApi.SEARCH_VALUE.set(searchValueList)
      },
      getValue(searchValue:string){
        if(searchValue) return searchValue
        return findItem  ? findItem.searchValue : ""
      }
    }
    valueApi.saveValue(searchValue)
    searchValue = valueApi.getValue(searchValue)
    return searchValue
  },
  getFulUrl(url:string,searchValue:string){
    let fulUrl = url
    if(searchValue){
      fulUrl += `?${searchValue}`
    }
    return fulUrl
  }
}  
const smartJumpApi = {
  // 智能跳转
  // 1.和系统库LastURL对比，判断是否需要智能补全
  isUseSmartJump(urlInfo:UrlInfo,routerArray:UrlInfo[]){
    if(!location.href.includes("localhost")) return false
    if(routerArray.length === 0 && !urlInfo.fulUrl) return false
    if(urlInfo.fulUrl && location.href === urlInfo.fulUrl) return false
    return true
  },

  jumpByCompleteUrl(findItem:UrlInfo){
    // 跳转前先储存信息
    mkApi.URL_INFO.set(findItem)
    if(!location.search && location.href !== findItem.fulUrl){
      location.href = findItem.fulUrl
    } 
  },
  // 3.路由输入不完整(通过pathName判断)
    // 3.1有urlInfo，与routerArray对比是否同一个项目，是=>跳转；否，跳转项目第一个路由
    // 2.2无urlInfo，则跳转至项目第一个路由里
  jumpByUnCompleteUrl(urlInfo:UrlInfo,routerArray:UrlInfo[]){
    if(!urlInfo.fulUrl) return this.jumpByRouterArrayFirstItem(routerArray)
    // 判断是否根路由
    let isHavePathName = (location.pathname && location.pathname !== "/")
    if(!isHavePathName) return location.href = urlInfo.fulUrl
    let findItem = routerArray.find(res => res.pathName === urlInfo.pathName)
    if(findItem) {
      location.href = urlInfo.fulUrl
    }else{
      this.jumpByRouterArrayFirstItem(routerArray)
    }
  },
  jumpByRouterArrayFirstItem(routerArray:UrlInfo[]){
    if(routerArray.length > 0){
      // 挑战前储存信息
      mkApi.URL_INFO.set(routerArray[0])
      location.href = routerArray[0].fulUrl
    }
  },
  smartJump(){
    const urlInfo = mkApi.URL_INFO.get()
    const routerArray = routerApi.getRouterArrayInfo()
    // 1.跳转前校验
    const jumpStatus = this.isUseSmartJump(urlInfo,routerArray)
    if(!jumpStatus) return
    const isHavePathName = (location.pathname && location.pathname !== "/")
    let findItem = routerArray.find(res => res.pathName === location.pathname)
    // 2.通过判断输入的url是否完整(通过pathName判断)进行智能跳转
    const isCompleteUrl = isHavePathName && findItem
    if(isCompleteUrl){
      // 2.1路由输入完整=> 通过找到的findItem跳转
      this.jumpByCompleteUrl(findItem)
    }else{
      // 2.2.路由输入不完整
        // 3.1有urlInfo，跳转
        // 2.2无urlInfo，则跳转至项目第一个路由里
      this.jumpByUnCompleteUrl(urlInfo,routerArray)
    }
  }
}
const routerApi = {
  // 获取dom上的路由信息
  getRouterDomInfo(){
    let vueApp: Vue_HTMLDivElement
     // 获取__vue__对象
    const __vue__ : HTMLDivElement = document.body.querySelector("div")
    const child__vue__: HTMLDivElement = document.body.querySelector("div #app")
    vueApp = child__vue__ || __vue__
    console.log('vueApp: ', vueApp);
    // 获取路由基础路径
    let rawBaseUrl:string
    if(vueApp?.__vue_app__){
      rawBaseUrl = vueApp.__vue_app__.config.globalProperties.$router.options.history.base
    }else{
      rawBaseUrl = vueApp?.__vue__?.$router?.options?.base ?? ""
    }
    let baseUrl = rawBaseUrl.replaceAll("//","/")
    if(rawBaseUrl.startsWith("/")) baseUrl = baseUrl.substring(1)
    if(rawBaseUrl.endsWith("/")) baseUrl = baseUrl.substring(0,baseUrl.length -1)
    // 获取 $router 信息
    let $router:any
    if(vueApp?.__vue_app__){
      $router = vueApp.__vue_app__.config.globalProperties.$router.options.routes
    }else{
      $router = vueApp?.__vue__?.$router?.options?.routes
    }
    // 过滤掉无用的路由信息
    if($router?.length > 0 ){
      $router = $router.filter((res:any) => !res.path.includes(":"))
    }
    return {
      baseUrl,
      routerList:$router
    }
  },
  // 获取包装好的路由信息
  getRouterArrayInfo():UrlInfo[]{
    const {baseUrl,routerList} = this.getRouterDomInfo()
    const searchValue = pathNameApi.getSearchValue(baseUrl)
    const routerArray:UrlInfo[] = routerList?.map((res: any):UrlInfo =>{
      const path = res.path ? res.path.replaceAll("//","/") : ""
      let url:string =`${location.protocol}//${location.host}/${baseUrl}${path}` 
      const pathName = (`/${baseUrl}${path}`).replaceAll("//","/")
      return {
        path:path,
        name:res.title ?? res?.meta?.title ?? res?.meta?.name ?? res?.name ?? path,
        fulUrl:pathNameApi.getFulUrl(url,searchValue),
        pathName:pathName,
        select:pathName === location.pathname,
        port:location.port
      }
    }) || []
    return routerArray
  },
  // 获取显示名称
  getActiveName():string{
    const saas_web_available = mkApi.SAAS_WEB_DEBUG_AVAILABLE.get()
    let that = this
    function showRouterName(){
      const routerList = that.getRouterArrayInfo()
      let routerItem = routerList.find((res:UrlInfo) => res.select)
      return routerItem ? (routerItem.name ? routerItem.name : "---/---"):  "---/---"
    }
    if(saas_web_available){
      let saasWebInfo = mkApi.SAAS_WEB_DEBUG_INFO.get()
      if(location.host.includes("localhost") && location.href.includes(saasWebInfo.serverName) && location.href.includes(saasWebInfo.authorizationId)) return saasWebInfo.authorizationId + "代理中"
      if(saasWebInfo.targetUrl.includes(location.host)) return saasWebInfo.serverName + "/" + saasWebInfo.authorizationId + "代理中"
      return showRouterName()
    }else{
      return showRouterName()
    } 
  },
  // 判断当前页面是否乾坤代理页面，返回服务名
  getProxyStatus(){
    // 先判断调试开关是否打开，然后判断代理地址是否包含服务名
    const saas_web_available = mkApi.SAAS_WEB_DEBUG_AVAILABLE.get()
    if(saas_web_available){
      let saasWebInfo = mkApi.SAAS_WEB_DEBUG_INFO.get()
      if(location.host.includes("localhost") && location.href.includes(saasWebInfo.serverName) && location.href.includes(saasWebInfo.authorizationId)) return true
      if(saasWebInfo.targetUrl.includes(location.host)) return true
      return false
    }else{
      return false
    }
    
  },
  start(){
    smartJumpApi.smartJump()
  }
}
export {
  routerApi
}
